#include "InterpolateLinear.h"

QRgb InterpolateLinear::getInterpolateResult (const QImage & src, const QPointF & p)
{
  int w = src.width ();
  int h = src.height ();
  if (p.x () < 0 || p.x () > w - 1 || p.y () < 0 || p.y () > h - 1)
    return 0;
  if (p.x () == w - 1 || p.y () == h - 1)
    return src.pixel ((int)p.x (), (int)p.y ());

  QPoint p0 ((int)p.x (), (int)p.y ());
  QPoint p1 ((int)p.x () + 1, (int)p.y ());
  QPoint p2 ((int)p.x () + 1, (int)p.y () + 1);
  QPoint p3 ((int)p.x (), (int)p.y () + 1);

  int bytesPerPixel = src.depth () / 8;
  __int32 colorRet;
  QRgb rgb0 = src.pixel (p0);
  QRgb rgb1 = src.pixel (p1);
  QRgb rgb2 = src.pixel (p2);
  QRgb rgb3 = src.pixel (p3);

  for (int i = 0; i < bytesPerPixel; ++i)
  {
    uchar c0 = ((uchar *)&(rgb0))[i];
    uchar c1 = ((uchar *)&(rgb1))[i];
    uchar c2 = ((uchar *)&(rgb2))[i];
    uchar c3 = ((uchar *)&(rgb3))[i];
    uchar t0 = ((float)(c1 - c0)) * (p.x () - p0.x ()) + c0;
    uchar t1 = ((float)(c2 - c3)) * (p.x () - p0.x ()) + c3;
    ((uchar*)&colorRet)[i] = ((float)(t1 - t0)) * (p.y () - p0.y ()) + t0;
  }

  return colorRet;

}
